use std::env;
use std::fs::File;
use std::io::Write;
use std::path::Path;

fn main() {
    println!("cargo:rerun-if-changed=.git/index");

    let out_dir = env::var("OUT_DIR").unwrap();
    let dest_path = Path::new(&out_dir).join("compile_time.rs");
    let mut f = File::create(&dest_path).unwrap();

    // 获得代码最后提交信息
    let output = std::process::Command::new("git")
        .args(&[
            "log",
            "-1",
            "--pretty=format:%H %an %cd %s",
            "--date=format:%Y/%m/%d %H:%M:%S",
        ])
        .output()
        .expect("Failed to execute git command");

    // 获得代码分支信息
    let branch = std::process::Command::new("git")
        .args(&["rev-parse", "--abbrev-ref", "HEAD"])
        .output()
        .expect("Failed to execute git command")
        .stdout;
    let branch = String::from_utf8(branch)
        .expect("Invalid UTF-8 sequence")
        .trim()
        .to_string();

    let git_log = String::from_utf8(output.stdout).expect("Invalid UTF-8 sequence");
    // 21705f198ad70d6a843362d859669247a04b8059 郭宇 2024/12/30 22:24:08 初始化落盘数据
    // 转换为：Git Commit Version: Commit: 21705f198, Author: 郭宇, Date: 2024/12/30 22:24:08, Info: 初始化落盘数据
    let git_version = git_log.split_whitespace().collect::<Vec<&str>>();
    let git_hash = &git_version[0][..9];
    let git_version = format!(
        "\nGit Commit Version: \nbranch: {branch}, \ncommit: {git_hash}, \ndate: {}, \ninfo: {}\n",
        format!("{} {}", git_version[2], git_version[3]),
        git_version[4..].join("")
    );

    f.write_all(format!("/// 编译GIT版本信息\n pub const COMPILE_GIT_VERSION_INFO: &str = r##\"{git_version}\"##;\n").as_bytes()).unwrap();
    f.write_all(
        format!("/// 编译GIT-hash信息\n pub const COMPILE_GIT_HASH_STR: &str = \"{git_hash}\";\n")
            .as_bytes(),
    )
    .unwrap();

    build_symbols_list();
}

fn build_symbols_list() {
    // 对于Linux，使用--dynamic-list选项
    #[cfg(target_os = "linux")]
    {
        println!("cargo:rustc-link-arg=-Wl,--dynamic-list=symbols.list");
    }

    // 对于macOS，使用-exported_symbols_list
    #[cfg(target_os = "macos")]
    {
        println!("cargo:rustc-link-arg=-Wl,-exported_symbols_list,symbols_mac.list");
        // macOS需要不同的符号列表格式
    }

    // Windows不使用特殊的链接选项
    // 我们改为使用运行时适配方法
}
